Difference between Hashtable and Dictionary
Difference between Hashtable and Dictionary
415
13-Jun-2024
Updated on 13-Jun-2024
Ashutosh Kumar Verma
13-Jun-2024Dictionary vs Hashtable in C#
In C#, Hashtable and Dictionary are used to store key-value pairs, but they have some differences in terms of functionality, implementation and features,
Dictionary
There are several points in Dictionary that make it different from Hashtable which are as follows,
Namespace- Dictionary is present in the
System.Collections.Genericnamespace.Type Safety- The
Dictionaryis type-safe, you must specify the data type for both the keys and the values when you declare it.Performance-
Dictionaryusually provides better performance thanHashtablesince it is a generic collection and avoids boxing/unboxing overheadNull Keys- the
Dictionarydoes not allow the null key but allows null values.Enumeration- Enumerating over a
dictionarywith foreach is more efficient than enumerating over ahashtable.Enumeration Order-
Dictionarydoes not guarantee the order of the elements whileHashtablealso does not preserve the order of the elements.Obsolete- The
dictionaryis a newer and preferred alternative to key-value pairs in most cases.Example-
Output-
Hashtable
There are also some points in Hashtable that differ from Dictionary which are as follow,
Namespace- Dictionary is present in the
System.Collectionsnamespace.Type Safety- The
Hashtableis not type-safe, because it allows any datatype for both key and value.Performance-
Hashtableuses a simple hash code algorithm that's why its performance is not as good as DictionaryNull Keys- The
Hashtableallows both the null key and null valueEnumeration- Hashtable needs boxing/unboxing, which can degrade performance during calculation.
Enumeration Order- The
Hashtabledoesn't preserve the order of the elements.Obsolete- The Hashtable is a part of an older non-generic collection framework in C#
Example-
Output-
Also, Read: Pascal Triangle